package com.dlc.yunguang.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import com.dlc.commonlibrary.adapter.BaseRecyclerAdapter;
import com.dlc.commonlibrary.ble.UHFR2000Helper;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.dialog.ReadNumsDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.yunguang.adapter.BuCaoAdapter;
import com.dlc.yunguang.adapter.decoration.RecyclerSpace;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.net.bean.OrderWashDetailBean;
import com.dlc.yunguang.net.bean.WashOrderDetailBean;
import com.dlc.yunguang.net.protocol.OrderProto;
import com.dlc.yunguang.R;
import com.seuic.uhf.EPC;
import com.trello.rxlifecycle.android.ActivityEvent;
import java.util.ArrayList;
import java.util.List;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class BuCaoJiaoJieActivity extends BaseActivity {
    @BindView(R.id.titleBar)
    TitleBar titleBar;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.orderno)
    TextView orderno;
    @BindView(R.id.hotel)
    TextView hotel;
    private BuCaoAdapter mAdapter;
    private String ordernoData;
    private DoResultDialog doResultDialog;
    private ReadNumsDialog doReadDialog;
    private String[] totalNum; //扫描订单二维码获取到的所有rfid
    private ArrayList<String> RfList = new ArrayList<>();//手持机读取的所有rfid
    private ArrayList<String> dataList = new ArrayList<>();//扫描订单二维码获取到的所有rfid
    private StringBuilder mStringBuilder;
    private Handler mHandler = new Handler();

    @Override
    protected int getLayoutID() {
        return R.layout.activity_bucao;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ordernoData = getIntent().getStringExtra("orderno");
        Log.e("MainA",ordernoData);
        titleBar.titleText.setText("布草交接");
        titleBar.leftExit(this);
        initRecyclerView();
        if(!TextUtils.isEmpty(ordernoData)){
            if(ordernoData.contains("W")){
                getOrderWashDetail();
            }else{
                getOrderDeliveryDetail();
            }
        }
        doReadRFID();
        doResult();
    }
    //rfids=0017187053B6,0001F1558064,0001F1557893,0001F15566ED,020991AFAB0B
    public void check(View view) {
        if (totalNum == null) {
            showToast("未获得订单数据");
            return;
        }
        rfidsList.clear();
        getData();
        //   rfidsList.add("TE2806890000000001C47035AF");
        //   rfidsList.add("TE2806890000000001C477310D");
        //   rfidsList.add("TE28068900000000393B7B571D");
        //   TYPE = 2;
        //   judgeData();

    }
    //我先请求交接之后，如果你返回交接成功的id，给我
    private ArrayList<String> rfidsList = new ArrayList<>();
    private int cashCount = 0;//获取到的缓存区的数量
    private int TYPE = 0;
    private boolean isBleStop = false;
    private boolean readState = false;
    private void getData(){

        readState = true;
        doReadDialog.showWorking(true);
        UHFR2000Helper.getInstance().readData(new UHFR2000Helper.BleCallBack() {
            @Override
            public void readDatas(List<EPC> data) {
                LogPlus.e("mEPCList="+data.toString());
                if (data.size() > 0){
                    doReadDialog.dismiss();
                    doResultDialog.showResultAndDismiss(true, 1000);
                    ArrayList<String> mList = new ArrayList<>();
                    String str = "";
                    for (EPC epc : data) {
                        str = epc.getId();
                        if (str.length() > 14) {
                            str = str.substring(str.length() - 12, str.length());
                            mList.add(str);
                        }
                    }

                    doResultDialog.dismiss();
                    startData(null, null);
                }else {
                    doReadDialog.dismiss();
                    doResultDialog.setFailedText("读取不到RFID");
                    doResultDialog.setFailedImage(R.mipmap.ic_error);
                    doResultDialog.showResultAndDismiss(false, 2000);

                }
            }

            @Override
            public void readNums(final int nums) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (readState) {
                            doReadDialog.showWorking(nums);
                        }
                    }
                });

            }
        });
    }





    private void startData(ArrayList<String> reduceList,ArrayList<String> addList){
        dataList.clear();
        for(int i = 0;i < totalNum.length;i++){
            dataList.add(totalNum[i]);
        }
        Intent intent = new Intent(BuCaoJiaoJieActivity.this, BuCaoResultActivity.class);
        // intent.putStringArrayListExtra("reduceList",  reduceList);
        //intent.putStringArrayListExtra("addList",  addList);
        intent.putStringArrayListExtra("dataList",  dataList);
        intent.putStringArrayListExtra("RfList",  RfList);
        intent.putExtra("orderno",ordernoData);
        startActivity(intent);
    }



    private void initRecyclerView() {
        mAdapter = new BuCaoAdapter();

        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, BaseRecyclerAdapter.CommonHolder holder,
                int position) {

            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.addItemDecoration(new RecyclerSpace(getResources(), 0, R.dimen.normal_24dp));
        mRecyclerView.setAdapter(mAdapter);
    }

    private void doReadRFID() {
        doReadDialog =
                ReadNumsDialog.newDialog(this)
                .setSuccessImage(R.mipmap.ic_success)
                .setSuccessText(getString(R.string.scan_over))
                .setButton("完成扫描", new ReadNumsDialog.OnClickButtonListener() {
                    @Override
                    public void onClickButton(ReadNumsDialog dialog) {
                        readState = false;
                        UHFR2000Helper.getInstance().stopRead();
                    }
                });

        doReadDialog.setCancelable(false);

    }
    private void doResult() {

        doResultDialog = DoResultDialog.newDialog(this)
            .setWorkingText(getString(R.string.commit_counting_result))
            .setSuccessImage(R.mipmap.ic_success)
            .setSuccessText(getString(R.string.commit_counting_result_success));

        doResultDialog.setCancelable(false);


    }

    public void getOrderWashDetail() {
        showLoadingDialog();
        OrderProto.get()
            .orderWashDetail(null,ordernoData)
            .subscribeOn(Schedulers.io())
            .compose(this.<WashOrderDetailBean>bindUntilEvent(ActivityEvent.DESTROY))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<WashOrderDetailBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                    dismissLoadingDialog();
                }

                @Override
                public void onNext(WashOrderDetailBean bean) {
                    dismissLoadingDialog();
                    if (bean.getCode() == 1) {
                        if (bean.getData().getSpec_group() != null) {
                            List<OrderWashDetailBean.DataBean.SpecGroupBean> list = new ArrayList<OrderWashDetailBean.DataBean.SpecGroupBean>();
                            List<WashOrderDetailBean.DataBean.SpecGroupBean> listWash = bean.getData().getSpec_group();
                            for (WashOrderDetailBean.DataBean.SpecGroupBean bean1 :listWash){
                                OrderWashDetailBean.DataBean.SpecGroupBean bean2 = new OrderWashDetailBean.DataBean.SpecGroupBean();
                                bean2.count = bean1.getCount();
                                bean2.spec = bean1.getSpec();
                                bean2.spec_id = bean1.getSpec_id();
                                bean2.title = bean1.getTitle();
                                list.add(bean2);
                            }
                            totalNum = bean.getData().getRfids().split(",");
                            mAdapter.setNewData(list);
                            orderno.setText(bean.getData().getOrderno());
                            hotel.setText(bean.getData().getHotel());

                        }
                    }else {
                        showOneToast(bean.getMsg());
                    }
                }
            });
    }

    public void getOrderDeliveryDetail() {
        showLoadingDialog();
        OrderProto.get()
            .orderDeliverDetail(null,ordernoData)
            .subscribeOn(Schedulers.io())
            .compose(this.<WashOrderDetailBean>bindUntilEvent(ActivityEvent.DESTROY))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<WashOrderDetailBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                    dismissLoadingDialog();
                }

                @Override
                public void onNext(WashOrderDetailBean bean) {
                    dismissLoadingDialog();
                    if (bean.getCode() == 1) {
                        if (bean.getData().getSpec_group() != null) {
                            List<OrderWashDetailBean.DataBean.SpecGroupBean> list = new ArrayList<OrderWashDetailBean.DataBean.SpecGroupBean>();
                            List<WashOrderDetailBean.DataBean.SpecGroupBean> listWash = bean.getData().getSpec_group();
                            for (WashOrderDetailBean.DataBean.SpecGroupBean bean1 :listWash){
                                OrderWashDetailBean.DataBean.SpecGroupBean bean2 = new OrderWashDetailBean.DataBean.SpecGroupBean();
                                bean2.count = bean1.getCount();
                                bean2.spec = bean1.getSpec();
                                bean2.spec_id = bean1.getSpec_id();
                                bean2.title = bean1.getTitle();
                                list.add(bean2);
                            }
                            mAdapter.setNewData(list);
                            orderno.setText(bean.getData().getOrderno());
                            hotel.setText(bean.getData().getHotel());
                            totalNum = bean.getData().getRfids().split(",");
                        }
                    }else {
                        showOneToast(bean.getMsg());
                    }
                }
            });
    }
}
